/**
 * 权限管理
 */
define(function (require, exports, module) {
    var $ = require("jquery");
    var util = require("util");
    var _ = require('underscore');
    var ui = require('ui');
    var environment = require('environment');

    var Permission = {
        init: function () {
            this._dataCallbacks = [];
            this._data = null;
            var $body = $('body');
            this._funcCodes = $body.attr('data-func-codes');

            this._pagePermission = $body.attr('data-permission');

            var self = this;
            this._getAppCodes(function (appCodesFromServer) {
                var appCodes = getAllAppCodes(appCodesFromServer);
                self._getData(appCodes);
            });

            function getAllAppCodes(appCodesFromServer) {
                var codes = $body.attr('data-app-codes');

                var arr = [];
                if (codes) {
                    arr = codes.split(',')
                }

                arr = arr.concat([
                    //可绑定的应用，需要通过接口返回
                    //'5003',//全民营销
                    //'5021',//认筹理财
                    //'5002',//移动销售
                    //'5008',//小蜜蜂
                    //'5001',//微楼书
                    //'5009',//微楼书（新版）
                    //'5006' //成员管理

                    '5007',//渠道管家
                    '5004',//O2O应用
                    '0000'//系统管理
                ]);

                if (appCodesFromServer && appCodesFromServer.length > 0) {
                    arr = arr.concat(appCodesFromServer);
                }

                //成员管理从属于移动销售
                if (util.inArray('5002', arr)) {
                    arr.push('5006');
                }

                return arr;
            }
        },
        /**
         * 获取公众号拥有应用
         * @param callback
         * @private
         */
        _getAppCodes: function (callback) {
            if (util.getToken()) {
                var url = environment.qmyx + G_CONFIG["api_prefix"] + "common/my-applicationto-project/get-applicationto-project";
                $.ajax({
                    url: url,
                    dataType: 'jsonp',
                    jsonp: 'callback',
                    data: {
                        token: util.getToken()
                    },
                    success: function (json) {
                        if (json.retCode == 0) {
                            var codes = [];
                            var data = json.data;
                            if (data) {
                                for (var key in data) {
                                    if (data.hasOwnProperty(key) && data[key] === true) {
                                        codes.push(key);
                                    }
                                }
                            }

                            callback(codes);
                        } else {
                            ui.showErrTip(json.errMsg);
                        }
                    }
                });
            } else {
                callback([]);
            }
        },
        _getData: function (appCodes) {
            var self = this;
            var data = {
                functionCodes: this._funcCodes,
                token: util.getToken()
            };
            if (appCodes) {
                data['appCodes'] = appCodes.join(',');
            }
            $.ajax({
                url: environment.qmyx + G_CONFIG.api_prefix + "identity/get-auth-actions-by-function-codes",
                dataType: 'jsonp',
                jsonp: 'callback',
                data: data,
                cache: false,
                success: function (res) {
                    if (res['retCode'] == 0) {
                        self._data = res['data'];
                        self._update(self._data);
                        self._fire();
                    }
                },
                error: function () {
                    self._showPermissionError();
                }
            })
        },
        _fire: function () {
            var callback;
            for (var i = 0; callback = this._dataCallbacks[i]; i++) {
                callback(this._data);
            }
            //清空dataCallbacks
            this._dataCallbacks = [];
        },
        /**
         * 获取权限数据
         * @param {function(Object)} callback
         */
        getData: function (callback) {
            this._dataCallbacks.push(callback);

            if (this._data) {
                this._fire();
            }
        },
        /**
         * 提示权限系统错误
         */
        _showPermissionError: function () {
            this.showTipAndForward('对不起，权限系统出现问题', '重新登录', '/login.shtml');
        },
        /**
         * 提示并跳转首页
         * @param {string} content
         * @param {string=} btnText
         * @param {string=} btnUrl
         */
        showTipAndForward: function (content, btnText, btnUrl) {
            btnUrl = btnUrl || '/';
            require.async("dialog", function (dialog) {
                dialog({
                    title: '提示',
                    fixed: true,
                    content: content,
                    width: 350,
                    okValue: '返回首页'||btnText,
                    cancelDisplay: false,
                    ok: function () {
                        location.href = btnUrl;
                        return true;
                    },
                    cancel: function () {
                        location.href = btnUrl;
                        return true;
                    }
                }).showModal();
            });
        },
        /**
         * 是否有权限访问页面
         * @param permissions
         * @returns {boolean}
         */
        hasPagePermission: function (permissions) {
            var pagePermission = this._pagePermission;

            if (typeof pagePermission === 'undefined' || pagePermission === 'all') {
                return true;
            }

            var item;
            for (var i = 0; item = permissions[i]; i++) {
                if (pagePermission == (item.funcCode + '-' + item.code)) {
                    return true;
                }
            }
            return false;
        },
        /**
         * @param {{functions:Array.<{appCode:string,funcCode:string,code:string}>,nav:Array.<string>}} data
         */
        _update: function (data) {
            var permissions = data.functions;
            var navPermissions = data.nav;

            var selBlockArr = [];
            var selInlineArr = [];
            var selInlineBlockArr = [];

            if (!this.hasPagePermission(permissions)) {
                util.showNoPagePermission();
                return;
            }

            function putClass(clsPart) {
                selBlockArr.push('.p-' + clsPart);
                selBlockArr.push('.p-' + clsPart + '-block');

                selInlineArr.push('.p-' + clsPart + '-inline');
                selInlineBlockArr.push('.p-' + clsPart + '-inline-block');
            }

            _.each(_.uniq(_.pluck(permissions, 'appCode')),function(val){
                putClass(val);
            });

            var item;

            for (var i = 0; item = permissions[i]; i++) {
                putClass(item.funcCode + '-' + item.code);
            }

            var navItem;
            for (var i = 0; navItem = navPermissions[i]; i++) {
                putClass(navItem);
            }

            $('head').append(
                '<style type="text/css">' +
                '.permission{display:none !important;}' +
                selBlockArr.join(',') + '{display:block !important;}' +
                selInlineArr.join(',') + '{display:inline !important;}' +
                selInlineBlockArr.join(',') + '{display:inline-block !important;}' +
                '</style>'
            )
        }
    };

    Permission.init();

    return Permission;
});